/*#################################################

Number Format | v1.0
Max Felker | max@bigroomstudios.com
James Roberts | http://jamesroberts.name/blog/2010/01/30/number-formatter-for-javascript-with-prototype/

Extends Math object to format number strings

Example: 

Math.format_number('420420.420',{
	decimals:2,
	currency:'$',
	format_whole:true,
	delim_whole:',',
	delim_decimal:'.'
});

#################################################*/

Object.extend(Math, {
			  
	format_number: function(number,options) {
		
		number_return = '';
		number_array = $A();
		number_array = String(number).split('.');
		
		var options = Object.extend({
			decimals:2,
			currency:'$',
			format_whole:true,
			delim_whole:',',
			delim_decimal:'.'
		},options);
		
		prefix = options.currency ? options.currency : '';
		
		whole_number = (typeof number_array[0]!='undefined') ? number_array[0] :'0';
		
		if(options.format_whole){
			var exp = /(\d+)(\d{3})/;
			while (exp.test(whole_number)) {
				whole_number = whole_number.replace(exp, '$1' + options.delim_whole + '$2');
			}
		}
		
		number_return += prefix + whole_number;
		
		if(options.decimals) {
			
			if(typeof number_array[1]!='undefined'){
				remainder = number_array[1];
			}else{
				remainder = '';
				for(var i=0;i<options.decimals;i++){
					remainder += '0'
				}
			}
			
			number_return += options.delim_decimal;
			
			var decimal_array = $A();
		
			for(var i = 0; i < options.decimals; i++){
				
				if(remainder.charAt(i) != '') {
					decimal_array[i] = remainder.charAt(i);
				} else {
					decimal_array[i] = '0';
				}
				
			}
			
			number_return += decimal_array.join("");
			
			return number_return;
			
		} else {
			return number_return;
		}
		
	}
	
});
